package sdk.org.apache.shiro.G2_使用.C10_SpringBoot集成_1登录和退出.shiro;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.springframework.stereotype.Component;

import com.titan.core.utils.cache.RedisUtils;
import com.titan.core.utils.data.FormatUtils;

/**
 * shiro session dao
 */
@Component
public class RedisShiroSessionDAO extends EnterpriseCacheSessionDAO {
    //创建session
    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = super.doCreate(session);
        final String key = getShiroSessionKey(sessionId.toString());
        setShiroSession(key, session);
        return sessionId;
    }

    //获取session
    @Override
    protected Session doReadSession(Serializable sessionId) {
        Session session = super.doReadSession(sessionId);
        if(session == null){
            final String key = getShiroSessionKey(sessionId.toString());
            session = getShiroSession(key);
        }
        return session;
    }

    //更新session
    @Override
    protected void doUpdate(Session session) {
        super.doUpdate(session);
        final String key = getShiroSessionKey(session.getId().toString());
        setShiroSession(key, session);
    }

    //删除session
    @Override
    protected void doDelete(Session session) {
        super.doDelete(session);
        final String key = getShiroSessionKey(session.getId().toString());
        RedisUtils.remove(key);
    }
    
    
    private final static Map<String,byte[]> cache = new HashMap<String,byte[]>();
    private Session getShiroSession(String key) {
        //byte[] bytes = RedisUtils.getBytes(key);
        byte[] bytes = cache.get(key);
        Session session = (Session)FormatUtils.byteArrayToObject(bytes);
        return session;
    }
    
    private void setShiroSession(String key, Session session){
        byte[] bytes = FormatUtils.objectToByteArray(session);
//        RedisUtils.set(key, bytes);
//        RedisUtils.expire(key, 60*60);      // 60分钟过期
        cache.put(key, bytes);
    }
    
    private static String getShiroSessionKey(String key){
        return "sessionid:" + key;
    }
}
